#!/bin/bash

# Copyright (C) 2006, 2007, 2008, 2009 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

# This is a test script to ease development and testing. It should NOT be used
# to update production machines. Password-less root login via SSH is required.

# Usage: upload.sh machine1 machine2

set -e

hosts=
while [[ "$#" -gt 0 ]]; do
  opt="$1"
  case "${opt}" in
    -h|--help)
      echo "Usage: $0 hosts..."
      exit 1
    ;;
    -*)
      echo "Unknown option: ${opt}" >&2
      exit 1
    ;;
    *)
      hosts="${hosts} ${opt}"
    ;;
  esac
  shift
done

installdir=$(mktemp -d)
trap "rm -rf ${installdir}" EXIT

# Install everything into a temporary directory
make install DESTDIR="${installdir}"

# Print list of all files
echo ---
( cd "${installdir}" && find | sort; )
echo ---

PREFIX='@PREFIX@'
PKGLIBDIR='@PKGLIBDIR@'
PKGPYTHONDIR='@PKGPYTHONDIR@'

# Upload everything to target machines
for host in ${hosts}; do
  (
  rsync -v -rlDc --exclude="*.py[oc]" --exclude="*.pdf" --exclude="*.html" \
    "${installdir}/${PREFIX}/" \
    root@${host}:${PREFIX}/ && \
  ssh root@${host} \
    "chmod 755 ${PKGLIBDIR} ${PKGPYTHONDIR} ${PKGLIBDIR}/* &&
     chmod 644 ${PKGPYTHONDIR}/* ${PKGPYTHONDIR}/app/* &&
     chmod 755 ${PKGPYTHONDIR}/app"
  ) &
done

# Wait for child processes
wait
